package com.example.rentsystem.servlet.api;

import com.example.rentsystem.entity.User;
import com.example.rentsystem.service.UserService;
import com.example.rentsystem.service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.regex.Pattern;

@WebServlet("/modify-user-info")
public class ModifyUserInfoServlet extends HttpServlet {

    UserService service;

    @Override
    public void init() throws ServletException {
        service = new UserServiceImpl();
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        HttpSession session = req.getSession();
        User user = (User) session.getAttribute("user");
        if (user == null) {
            session.setAttribute("login-first", true);
            resp.sendRedirect("login");
            return;
        }
        String id = req.getParameter("id");
        if (id != null && !id.equals("")) {
            User u = service.getUserById(Integer.parseInt(id));
            String name = req.getParameter("name");
            String account = req.getParameter("account");
            String phone = req.getParameter("phone");
            if (!name.equals(u.getName()) && service.userNameExist(name)) {
                session.setAttribute("username-exist", true);
                resp.sendRedirect("personal-info?id=" + u.getId());
                return;
            } else if (!name.equals("")) {
                if (!(name.length() >= 2 && name.length() <= 6)) {
                    session.setAttribute("name-short", true);
                    resp.sendRedirect("personal-info?id=" + u.getId());
                    return;
                }
                u.setName(name);

            }
            if (!account.equals(u.getAccount()) && service.accountExist(account)) {
                session.setAttribute("account-exist", true);
                resp.sendRedirect("personal-info?id=" + u.getId());
                return;
            } else if (!account.equals("")) u.setAccount(account);
            if (!phone.equals(u.getPhone()) && !isValidPhoneNumber(phone)) {
                session.setAttribute("invalid-phone", true);
                resp.sendRedirect("personal-info?id=" + u.getId());
                return;
            } else if (!phone.equals("")) u.setPhone(phone);
            service.editUser(u);
            resp.sendRedirect("personal-info?id=" + u.getId());
        }
    }

    public static boolean isValidPhoneNumber(String phoneNumber) {
        if ((phoneNumber != null) && (!phoneNumber.isEmpty())) {
            return Pattern.matches("^1[3-9]\\d{9}$", phoneNumber);
        }
        return false;
    }
}
